package com.stars.easyms.feign.request;

import com.alibaba.fastjson.JSON;
import com.stars.easyms.base.constant.HttpHeaderConstants;
import com.stars.easyms.base.http.EasyMsRequestSynchronizationManager;
import com.stars.easyms.base.util.DateTimeUtil;
import com.stars.easyms.base.util.SerialNumberUtil;
import com.stars.easyms.base.util.SpringBootUtil;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>className: BaseRequestInterceptor</p>
 * <p>description: 基础feign调用请求拦截器</p>
 *
 * @author guoguifang
 * @version 1.6.3
 * @date 2020/9/17 2:34 下午
 */
abstract class BaseFeignRequestInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    void handleRequest(RequestTemplate requestTemplate, Object object) {
        // 如果已经设置了traceId则不再重复设置
        if (requestTemplate.headers().get(HttpHeaderConstants.TRACE_KEY) != null) {
            return;
        }

        // 获取全局追踪ID，用于微服务日志全链路跟踪，如果为空则创建一个
        String traceId = SerialNumberUtil.getSerialNumber(EasyMsRequestSynchronizationManager.getTraceId());
        String applicationName = SpringBootUtil.getApplicationName();
        String requestId = SerialNumberUtil.getSerialNumber();
        String requestTime = DateTimeUtil.now();

        // 获取响应系统及请求路径
        String responseSys = requestTemplate.feignTarget().name();
        responseSys = responseSys.startsWith("http://") ? responseSys.substring(7) : responseSys;
        int responseSysIndex = requestTemplate.url().indexOf(responseSys);
        String requestPath = responseSysIndex < 0 ? requestTemplate.url() : requestTemplate.url().substring(responseSysIndex + responseSys.length());

        // 将参数放入请求头中
        requestTemplate.header(HttpHeaderConstants.TRACE_KEY, traceId);
        requestTemplate.header(HttpHeaderConstants.HEADER_KEY_REQUEST_PATH, requestPath);
        requestTemplate.header(HttpHeaderConstants.HEADER_KEY_REQUEST_SYS, applicationName);
        requestTemplate.header(HttpHeaderConstants.HEADER_KEY_RESPONSE_SYS, responseSys);
        requestTemplate.header(HttpHeaderConstants.HEADER_KEY_REQUEST_ID, requestId);
        requestTemplate.header(HttpHeaderConstants.HEADER_KEY_REQUEST_TIME, requestTime);

        // 将用户信息放入请求头中
        String userInfo = EasyMsRequestSynchronizationManager.getCurrentUserInfo();
        if (userInfo != null) {
            requestTemplate.header(HttpHeaderConstants.HEADER_KEY_USER_INFO, userInfo);
        }

        // 记录请求日志
        logger.info("[调用服务-请求]-[请求地址:{}]-[请求系统:{}]-[服务系统:{}]-[请求ID:{}]-[请求时间:{}]{}",
                requestPath, applicationName, responseSys, requestId, requestTime,
                object == null ? "" : "-请求数据:" + JSON.toJSONString(object));
    }

}
